import axios, { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios';
import { message, Modal } from 'antd';
import Config from 'common/config'

let pending: any[] = []
let cancelToken = axios.CancelToken
let removePending = (ever: any) => {
    for (let p in pending) {
        if (pending[p].u === ever.url + '&' + ever.method) { //当当前请求在数组中存在时执行函数体
            pending[p].f(); //执行取消操作
            pending.splice(Number(p), 1); //把这条记录从数组中移除
        }
    }
}
axios.defaults.baseURL = Config.API_URL
// axios.defaults.withCredentials = true

// 添加请求拦截器
axios.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        //   const token = getToken();

        //   // 获取用户token，用于校验
        //   /* eslint-disable  no-param-reassign */
        //   if (token) {
        //     config.headers.token = token;
        //   }
        removePending(config); //在一个ajax发送前执行一下取消操作
        config.cancelToken = new cancelToken((c) => {
            // 这里的ajax标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
            pending.push({ u: config.url + '&' + config.method, f: c });
        });
        return config;
    },
    (error: AxiosError) => Promise.reject(error),
);

axios.interceptors.response.use(
    (response: AxiosResponse) => {
        removePending(response.config);
        if (!response.data) {
            return Promise.resolve(response);
        }

        // 登录已过期或者未登录
        if (response.data.code === Config.LOGIN_EXPIRE) {
            Modal.confirm({
                title: '系统提示',
                content: response.data.msg,
                cancelText: '取消',
                okText: '重新登录',
                onOk() {
                    Modal.destroyAll()
                    window.location.href = `${window.location.origin + window.location.pathname}#/login`;
                },
                onCancel() { },
            });

            return Promise.reject(response.data.msg);
        }

        // 请求成功
        if (response.data.http_code === Config.SUCCESS_CODE) {
            return response.data.data as any;
        }
        if (response.data.size) {
            return response
        }

        // 请求成功，状态不为成功时
        message.error(response.data.msg);

        return Promise.reject(response.data);
    },
    (error: any) => {
        if (error.__CANCEL__) return
        message.error(error.message);
        return Promise.reject(error);
    },
);

export const Get = (url: string, params?: any): Promise<any> => {
    return axios.request({
        method: 'get',
        url,
        params
    })
}
export const Post = (url: string, params?: any): Promise<any> => {
    return axios.request({
        method: 'post',
        url,
        params
    })
}
export const PostJson = (url: string, data: any): Promise<any> => {
    return axios.request({
        method: 'post',
        url,
        data
    })
}
export const PostForm = (url: string, data: any): Promise<any> => {
    let form = new FormData()
    Object.keys(data).forEach(key => {
        form.append(key, data[key])
    })
    return axios.request({
        method: 'post',
        url,
        data: form
    })
}

export const GetBlob = (url: string, params: any): Promise<any> => {
    return axios.request({
        method: 'get',
        url,
        params,
        responseType: 'blob'
    })
}